<template>
  <ElDialog
    v-model="dialogVisible"
    :title="title"
    width="600"
    :before-close="handleClose"
    :close-on-click-modal="false"
  >
    <div class="searchTable">
      <ElForm
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        label-width="auto"
        class="search-color"
      >
        <ElRow>
          <ElCol :span="24">
            <ElFormItem label="航线名称：" prop="airlineName">
              <ElInput
                maxlength="20"
                v-model="ruleForm.airlineName"
                placeholder="请输入航线名称"
                @keydown.enter.prevent
              />
            </ElFormItem>
          </ElCol>
          <ElCol :span="24">
            <ElFormItem label="航线类型：" prop="airlineType">
              <section v-if="title == '添加航线'">
                <div style="display: flex">
                  <div
                    class="airlineType"
                    :class="
                      ruleForm.airlineType === '0' ? 'airlineTypeColor' : ''
                    "
                    @click="changeType('0')"
                  >
                    <img src="/static/airbg2.png" alt="点状航线" />
                    <div>
                      <p class="btn">点状航线</p>
                    </div>
                  </div>

                  <div
                    class="airlineType"
                    :class="
                      ruleForm.airlineType === '1' ? 'airlineTypeColor' : ''
                    "
                    @click="changeType('1')"
                  >
                    <img src="/static/airbg1.png" alt="面状航线" />
                    <div>
                      <p class="btn">面状航线</p>
                    </div>
                  </div>
                </div>
              </section>
              <section v-else>
                <div style="display: flex">
                  <div
                    v-if="ruleForm.airlineType === '0' ? true : false"
                    class="airlineType"
                    :class="
                      ruleForm.airlineType === '0'
                        ? 'airlineTypeColor'
                        : 'not-allowed'
                    "
                  >
                    <img src="/static/airbg2.png" alt="点状航线" />
                    <div>
                      <p class="btn">点状航线</p>
                    </div>
                  </div>

                  <div
                    v-if="ruleForm.airlineType === '1' ? true : false"
                    class="airlineType"
                    :class="
                      ruleForm.airlineType === '1'
                        ? 'airlineTypeColor'
                        : 'not-allowed'
                    "
                  >
                    <img src="/static/airbg1.png" alt="面状航线" />
                    <div>
                      <p class="btn">面状航线</p>
                    </div>
                  </div>
                </div>
              </section>
            </ElFormItem>
          </ElCol>
          <ElCol :span="24">
            <ElFormItem label="无人机品牌：" prop="brandId">
              <ElSelect
                v-model="ruleForm.brandId"
                placeholder="请选择无人机品牌"
                @change="changeBrand"
              >
                <ElOption
                  v-for="item in brandOptions"
                  :key="item.id"
                  :label="item.brandName"
                  :value="item.id"
                />
              </ElSelect>
            </ElFormItem>
          </ElCol>
          <ElCol :span="24">
            <ElFormItem label="系列：" prop="seriesId">
              <div class="list">
                <div
                  v-for="item in seriesList"
                  :key="item.id"
                  class="list-item"
                  :class="{ active: ruleForm.seriesId === item.id }"
                  @click="selectSeries(item)"
                >
                  {{ item.seriesName }}
                </div>
              </div>
            </ElFormItem>
          </ElCol>
          <ElCol :span="24">
            <ElFormItem label="型号：" prop="modelId">
              <div class="list">
                <div
                  v-for="model in currentModels"
                  :key="model.id"
                  class="list-item"
                  :class="{ active: ruleForm.modelId === model.id }"
                  @click="selectModel(model)"
                >
                  {{ model.modelName }}
                </div>
              </div>
            </ElFormItem>
          </ElCol>
        </ElRow>
      </ElForm>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <ElButton class="b-r-4" @click="resetForm(ruleFormRef)">取消</ElButton>
        <ElButton class="b-r-4" type="primary" @click="mapClick(ruleFormRef)">
          下一步
        </ElButton>
      </div>
    </template>
  </ElDialog>
</template>
<script setup>
import {
  ElDialog,
  ElButton,
  ElForm,
  ElFormItem,
  ElInput,
  ElMessage,
  ElRow,
  ElCol,
  ElSelect,
  ElOption,
} from "element-plus";
import { onMounted, reactive, ref } from "vue";
import { getBrandList, getModelList, addName } from "#/api/task/airline";
import { router } from "#/router";
const dialogVisible = ref(false);
const title = ref("添加航线");
const ruleFormRef = ref();
const ruleForm = reactive({
  id: "",
  airlineName: "",
  airlineType: "0",
  brandId: "",
  seriesId: "",
  modelId: "",
});
const brandOptions = ref([]);
const seriesList = ref([]);
const currentModels = ref([]);
const rules = reactive({
  airlineName: [
    { required: true, message: "请输入航线名称", trigger: "blur" },
    { max: 20, message: "航线名称不能超过20个字符", trigger: "blur" },
    // 添加空格验证规则
    {
      validator: (rule, value, callback) => {
        if (value && value.includes(" ")) {
          callback(new Error("航线名称不能包含空格"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
  airlineType: [
    { required: true, message: "请选择航线类型", trigger: "change" },
  ],
  brandId: [{ required: true, message: "请选择无人机品牌", trigger: "change" }],
  seriesId: [{ required: true, message: "请选择系列", trigger: "change" }],
  modelId: [{ required: true, message: "请选择型号", trigger: "change" }],
});
const addDialog = () => {
  dialogVisible.value = true;
  title.value = "添加航线";

  // 重置表单
  ruleFormRef.value?.resetFields();

  // 重新加载品牌列表并选择默认值
  getList();
};

const editDialog = async (obj) => {
  dialogVisible.value = true;
  title.value = "编辑航线";

  // 重置表单
  ruleFormRef.value?.resetFields();

  // 先加载品牌列表
  await getList();

  // 设置编辑对象的值
  ruleForm.id = obj.id;
  ruleForm.airlineName = obj.airlineName;
  ruleForm.airlineCode = obj.airlineCode;

  // 设置航线类型
  if (obj.airlineType == "点状航线") {
    ruleForm.airlineType = "0";
  } else {
    ruleForm.airlineType = "1";
  }

  // 如果有品牌ID，则设置并加载对应的系列和型号
  if (obj.brandId) {
    ruleForm.brandId = obj.brandId;
    await getSeriesByBrandId();

    // 如果有系列ID，则设置并加载对应的型号
    if (obj.seriesId) {
      ruleForm.seriesId = obj.seriesId;
      const selectedSeries = seriesList.value.find(
        (series) => series.id === obj.seriesId
      );
      if (selectedSeries) {
        currentModels.value = selectedSeries.models || [];

        // 如果有型号ID，则设置
        if (obj.modelId) {
          ruleForm.modelId = obj.modelId;
        }
      }
    }
  }
};

defineExpose({ addDialog, editDialog });

const resetForm = () => {
  ruleFormRef.value.resetFields();
  dialogVisible.value = false;

  // 清空系列和型号列表
  seriesList.value = [];
  currentModels.value = [];
};
const handleClose = () => {
  dialogVisible.value = false;

  // 清空系列和型号列表
  seriesList.value = [];
  currentModels.value = [];
};
const changeType = (item) => {
  ruleForm.airlineType = item;
};

// 保存航线名称相关字段
const saveAirlineNameAdd = async () => {
  try {
    const params = {
      airlineName: ruleForm.airlineName,
      airlineType: ruleForm.airlineType,
      brandId: ruleForm.brandId,
      seriesId: ruleForm.seriesId,
      modelId: ruleForm.modelId,
    };

    const response = await addName(params);

    // 检查响应状态
    if (response.code === 200) {
      ElMessage.success("航线名称保存成功");
      return { success: true, data: response.data };
    } else {
      // 接口返回业务错误
      const errorMsg = response.message || response.msg || "保存失败";
      ElMessage.error(errorMsg);
      return { success: false, error: errorMsg };
    }
  } catch (err) {
    const errorMsg = err.message || "保存失败";
    ElMessage.error("保存失败: " + errorMsg);
    return { success: false, error: errorMsg };
  }
};
// const mapClick = async (formEl) => {
//   if (!formEl) return;
//   await formEl.validate((valid, fields) => {
//     if (valid) {
//       // 点状航线
//       if (ruleForm.airlineType == "0") {
//         if (title.value == "添加航线") {
//           router.push({
//             name: "RouteDetail",
//             query: {
//               airlineType: ruleForm.airlineType,
//               airlineName: ruleForm.airlineName,
//               brandId: ruleForm.brandId,
//               seriesId: ruleForm.seriesId,
//               modelId: ruleForm.modelId,
//             },
//           });
//         } else {
//           router.push({
//             name: "RouteDetail",
//             query: {
//               id: ruleForm.id,
//               airlineType: ruleForm.airlineType,
//               airlineName: ruleForm.airlineName,
//               brandId: ruleForm.brandId,
//               seriesId: ruleForm.seriesId,
//               modelId: ruleForm.modelId,
//             },
//           });
//         }
//       }
//       // 面状航线
//       else {
//         if (title.value == "添加航线") {
//           router.push({
//             name: "RouteDetailFace",
//             query: {
//               airlineType: ruleForm.airlineType,
//               airlineName: ruleForm.airlineName,
//               brandId: ruleForm.brandId,
//               seriesId: ruleForm.seriesId,
//               modelId: ruleForm.modelId,
//             },
//           });
//         } else {
//           router.push({
//             name: "RouteDetailFace",
//             query: {
//               id: ruleForm.id,
//               airlineCode: ruleForm.airlineCode,
//               airlineType: ruleForm.airlineType,
//               airlineName: ruleForm.airlineName,
//               brandId: ruleForm.brandId,
//               seriesId: ruleForm.seriesId,
//               modelId: ruleForm.modelId,
//             },
//           });
//         }
//       }
//     } else {
//       console.log("error submit!", fields);
//     }
//   });
// };

const mapClick = async (formEl) => {
  if (!formEl) return;
  
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      // 判断是添加还是编辑
      if (title.value == "添加航线") {
        // 添加航线时，先保存航线名称相关信息
        try {
          const saveResult = await saveAirlineNameAdd();
          
          if (saveResult.success) {
            ElMessage.success("航线信息保存成功");
            // 保存成功后跳转到详情页
            navigateToDetail(saveResult.data?.id);
          } else {
            // 保存失败，不跳转
            return;
          }
        } catch (err) {
          ElMessage.error("保存失败: " + (err.message || "未知错误"));
          return; // 保存失败不跳转
        }
      } else {
        // 编辑航线时，直接跳转到详情页
        navigateToDetail(ruleForm.id);
      }
    } else {
      console.log("error submit!", fields);
    }
  });
};

// 提取跳转逻辑到单独的函数
const navigateToDetail = (savedId = null) => {
  // 点状航线
  if (ruleForm.airlineType == "0") {
    if (title.value == "添加航线") {
      router.push({
        name: "RouteDetail",
        query: {
          airlineType: ruleForm.airlineType,
          airlineName: ruleForm.airlineName,
          brandId: ruleForm.brandId,
          seriesId: ruleForm.seriesId,
          modelId: ruleForm.modelId,
          // 如果有保存后的id，也传递过去
          id: savedId || undefined
        },
      });
    } else {
      router.push({
        name: "RouteDetail",
        query: {
          id: ruleForm.id,
          airlineType: ruleForm.airlineType,
          airlineName: ruleForm.airlineName,
          brandId: ruleForm.brandId,
          seriesId: ruleForm.seriesId,
          modelId: ruleForm.modelId,
        },
      });
    }
  }
  // 面状航线
  else {
    if (title.value == "添加航线") {
      router.push({
        name: "RouteDetailFace",
        query: {
          airlineType: ruleForm.airlineType,
          airlineName: ruleForm.airlineName,
          brandId: ruleForm.brandId,
          seriesId: ruleForm.seriesId,
          modelId: ruleForm.modelId,
          // 如果有保存后的id，也传递过去
          id: savedId || undefined
        },
      });
    } else {
      router.push({
        name: "RouteDetailFace",
        query: {
          id: ruleForm.id,
          airlineCode: ruleForm.airlineCode,
          airlineType: ruleForm.airlineType,
          airlineName: ruleForm.airlineName,
          brandId: ruleForm.brandId,
          seriesId: ruleForm.seriesId,
          modelId: ruleForm.modelId,
        },
      });
    }
  }
  
  // 关闭对话框
  dialogVisible.value = false;
};

const getList = async () => {
  try {
    const { data } = await getBrandList();
    brandOptions.value = data;

    // 默认选中第一个品牌
    if (data && data.length > 0) {
      ruleForm.brandId = data[0].id;
      // 获取第一个品牌的系列列表
      await getSeriesByBrandId();
    }
  } catch (error) {
    ElMessage.error("获取品牌列表失败");
    console.error(error);
  }
};

// 获取系列列表
const getSeriesByBrandId = async () => {
  if (!ruleForm.brandId) return;

  const params = {
    brandId: ruleForm.brandId,
  };

  try {
    const { data } = await getModelList(params);
    seriesList.value = data || [];

    // 默认选中第一个系列
    if (data && data.length > 0) {
      const firstSeries = data[0];
      ruleForm.seriesId = firstSeries.id;

      // 获取第一个系列的型号列表
      currentModels.value = firstSeries.models || [];

      // 默认选中第一个型号
      if (firstSeries.models && firstSeries.models.length > 0) {
        ruleForm.modelId = firstSeries.models[0].id;
      }
    }
  } catch (error) {
    ElMessage.error("获取系列列表失败");
    console.error(error);
  }
};

const changeBrand = async () => {
  if (!ruleForm.brandId) {
    seriesList.value = [];
    currentModels.value = [];
    ruleForm.seriesId = "";
    ruleForm.modelId = "";
    return;
  }

  await getSeriesByBrandId();
};

const selectSeries = (series) => {
  ruleForm.seriesId = series.id;
  currentModels.value = series.models || [];

  // 默认选择第一个型号
  if (series.models && series.models.length > 0) {
    ruleForm.modelId = series.models[0].id;
  } else {
    ruleForm.modelId = "";
  }
};

const selectModel = (model) => {
  ruleForm.modelId = model.id;
};

onMounted(() => {
  getList();
});
</script>
<style scope lang="scss">
.airlineType {
  padding: 21px 31px !important;
  margin-right: 20px;
  text-align: center;
  cursor: pointer;
  border: 1px solid #ccc;
  border-radius: 4px;

  &:hover {
    background: #e3f1ff;
    border: 1px solid #1989fa;

    .btn {
      color: #1989fa;
    }
  }

  &:active {
    background: #e3f1ff;
    border: 1px solid #1989fa;

    .btn {
      color: #1989fa;
    }
  }

  .btn {
    margin-top: 10px;
  }

  img {
    width: 33px;
    height: 33px;
    margin: auto;
  }
}

.airlineTypeColor {
  border: 1px solid #006be6;

  .btn {
    color: #006be6;
  }
}

.not-allowed {
  cursor: not-allowed;
  opacity: 0.5;
}

.not-allowed:hover {
  cursor: not-allowed;
  background-color: transparent;
  border-color: #ccc;
  opacity: 0.5;

  .btn {
    color: #303133;
  }
}

/* 系列和型号列表样式 */
.list {
  width: 100%;
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 10px;
  margin-bottom: 10px;
}

.list-item {
  padding: 8px 10px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
  text-align: center;
  min-height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;

  &:hover {
    background: #e3f1ff;
    border-color: #1989fa;
    color: #1989fa;
  }

  &.active {
    background: #e3f1ff;
    border-color: #1989fa;
    color: #1989fa;
  }

  &::marker {
    content: none;
  }
}

/* 响应式处理 */
@media (max-width: 500px) {
  .list {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (max-width: 350px) {
  .list {
    grid-template-columns: 1fr;
  }
}
</style>
